package ma.jeetconsulting.pocs.service;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarFile;

import ma.jeetconsulting.pocs.dependency.util.JARReader;

import org.apache.maven.model.Dependency;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CodeAnalyzerImpl implements CodeAnalyzer {

	private static final String UTF_8 = "UTF-8";

	private static final String FILE_ENCODING = "file.encoding";

	private static final String JAVA_EXTENSION = ".java";
	
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public ModuleReport makeObsoleteDependenciesReportFor( List<Dependency> dependencies, String projectPath) {
		try {
		JARReader jarReader = new JARReader();
		List<String> packages = new ArrayList<>();
		for (Dependency dependency : dependencies) {
			JarFile file = jarReader.getJarFile(dependency);
			packages.addAll(jarReader.getPackages(file));
		}

		List<JavaFile> result = new ArrayList<>();

			for (String javaFilePath : getAllJavaFilesPaths(new File(
					projectPath))) {
				JavaFile javaFile = getJavaFile(javaFilePath);
				if (javaFile.containsAnyOfThesesPackages(packages))
					result.add(javaFile);
			}
			return new ModuleReport(result);

		} catch (IOException | ParseException e) {
			logger.error("An error occur when when reading or parsing a module : ", e);
		}
		return null;
	}


	private JavaFile getJavaFile(String pathname) throws IOException {
		return new JavaFile(new File(pathname), getEncoding());
	}

	private String getEncoding() {
		return System.getProperty(FILE_ENCODING, UTF_8);
	}

	private List<String> getAllJavaFilesPaths(final File folder) {
		List<String> javaFiles = new ArrayList<>();

		for (final File fileEntry : folder.listFiles()) {
			if (fileEntry.isDirectory()) {
				javaFiles.addAll(getAllJavaFilesPaths(fileEntry));
			} else if (fileEntry.getPath().endsWith(JAVA_EXTENSION)) {
				javaFiles.add(fileEntry.getPath());
			}
		}

		return javaFiles;
	}

}
